//
//  DAFeedbackFormController.m
//  Created by David Aspinall on 01/04/09.
//  Copyright 2009 Plan-B Software.  
//  Some rights reserved: <http://opensource.org/licenses/mit-license.php>

// based on code 
/*******************************************************************************
 JRFeedbackController.h
 Copyright (c) 2008 Jonathan 'Wolf' Rentzsch: <http://rentzsch.com>
 Some rights reserved: <http://opensource.org/licenses/mit-license.php>
 
 ***************************************************************************/
//

#import "DAFeedbackFormController.h"
#import <AddressBook/AddressBook.h>
#import "NSURLRequest+Additions.h"


DAFeedbackFormController *gFeedbackController = nil;

NSString *JRFeedbackType[JRFeedbackController_SectionCount] = {
	@"BUG", // JRFeedbackController_BugReport
	@"FEATURE", // JRFeedbackController_FeatureRequest
	@"SUPPORT" // JRFeedbackController_SupportRequest
};

@implementation DAFeedbackFormController

+ (void)showFeedback 
{
    if (gFeedbackController == nil)
	{
        gFeedbackController = [[DAFeedbackFormController alloc] init];
    }
    [gFeedbackController showWindow:self];
}

- (id)init 
{
    self = [super initWithWindowNibName:@"FeedbackForm"];
    if (self) 
	{
        //[self window];
    }
    return self;
}

- (void)windowDidLoad
{
	NSString *title = [NSString stringWithFormat:@"%@ Feedback", [[NSProcessInfo processInfo] processName]];
	
    [[self window] setTitle:title];
	[textView setString:title];
        
    ABMutableMultiValue *emailAddresses = [[[ABAddressBook sharedAddressBook] me] valueForProperty:kABEmailProperty];
    unsigned addyIndex = 0, addyCount = [emailAddresses count];
    for (; addyIndex < addyCount; addyIndex++) 
	{
        [emailAddressComboBox addItemWithObjectValue:[emailAddresses valueAtIndex:addyIndex]];
    }
    [emailAddressComboBox selectItemAtIndex:0];
	
}

- (IBAction)switchSectionAction:(NSSegmentedControl*)sender 
{
    currentSection = [sender selectedSegment];
	
	NSString *title = [NSString stringWithFormat:@"%@ %@", [[NSProcessInfo processInfo] processName], JRFeedbackType[currentSection]];
	
    [[self window] setTitle:title];
	[textView setString:title];
	
    [textView moveToBeginningOfDocument:self];
    
    if (JRFeedbackController_SupportRequest == currentSection) 
	{
        [includeEmailAddressCheckbox setIntValue:YES];
    }
}

- (IBAction)submitAction:(id)sender 
{
    [textView setEditable:NO];
    [progress startAnimation:self];
	[self postFeedback];
}

- (void)postFeedback 
{
    NSString *postURL = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"DAFeedbackURL"];
    if ([[NSUserDefaults standardUserDefaults] stringForKey:@"DAFeedbackURL"]) 
	{
        postURL = [[NSUserDefaults standardUserDefaults] stringForKey:@"DAFeedbackURL"];
    }
    
    NSString *email = [includeEmailAddressCheckbox intValue] ? [emailAddressComboBox stringValue] : @"<email suppressed>";
    NSDictionary *form = [NSDictionary dictionaryWithObjectsAndKeys:
                          JRFeedbackType[currentSection], @"feedbackType",
                          [textView string], @"feedback",
                          email, @"email",
                          [[NSProcessInfo processInfo] processName], @"appName",
                          [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"], @"bundleID",
                          [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"], @"version",
                          nil];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:postURL] postForm:form];
    [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)closeFeedback 
{
    if (gFeedbackController) 
	{
        assert(gFeedbackController == self);
        [[gFeedbackController window] orderOut:self];
        [gFeedbackController release];
        gFeedbackController = nil;
    }
}

- (IBAction)cancelAction:(id)sender 
{
    [self closeFeedback];
}

- (void)connectionDidFinishLoading:(NSURLConnection*)connection 
{
    // TODO Drop Thank you sheet
    NSLog(@"-[DAFeedback connectionDidFinishLoading:%@]", connection);
    [self closeFeedback];
}

- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error 
{
    NSLog(@"-[DAFeedback connection:didFailWithError:%@]", error);
    [self closeFeedback];
}

- (void)windowWillClose:(NSNotification*)notification 
{
    [self closeFeedback];
}

@end
